from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
import settings, models, cgi, logging
from django.utils import simplejson
from handlers.poi import POI

class ShowCommentsHandler(webapp.RequestHandler):
    def get(self):
        poi_id = cgi.escape(self.request.get('poi_id'))
        template_values = settings.base_template_data(self.request)
        if poi_id:
            poi = db.get(db.Key.from_path('POI',long(poi_id)))
        else:
            poi = None
        if not(poi):
            template_values['poi'] = None
        elif poi.private and poi.user.user!=template_values['user']:
            template_values['unauth'] = True
        else:
            template_values['poi'] = poi
            template_values['comments'] = [comment for comment in models.Comment.all()]#[db.get(comment) for comment in poi.comments]
        path = settings.template_path('comments')
        self.response.out.write(template.render(path, template_values))

class AddCommentsHandler(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-type'] = 'text/javascript; charset=utf-8'
        poi_id = cgi.escape(self.request.get('poi_id'))
        comment = cgi.escape(self.request.get('comment'))
        template_values = settings.base_template_data(self.request)
        d = None
        if poi_id:
            poi = db.get(db.Key.from_path('POI',long(poi_id)))
        elif not(poi_id):
            d = {'error': "POI ID required"}
        elif not(comment):
            d = {'error': "Comment required"}
        if not(poi):
            d = {'error': "Non existing POI"}
        elif poi.private and poi.user.user!=template_values['user']:
            d = {'error': "You are not authorized to comment on this POI"}
        else:
            comment_obj = db.run_in_transaction(transact,comment,template_values['local_user'],poi)
            d = {'comment': comment_obj.comment, 'user': comment_obj.user.user.nickname()}
        self.response.out.write(simplejson.dumps(d))

application = webapp.WSGIApplication(
		[('/comments',ShowCommentsHandler),
		('/add_comment',AddCommentsHandler)],
		debug=settings.debug)

def main():
	run_wsgi_app(application)

if __name__=='__main__':
	main()
	
	
def transact(comment,user,poi):
    comment_obj = models.Comment(parent=poi,comment=comment,user=user)
    comment_obj.put()
    poi.comments.append(comment_obj.key())
    poi.put()
    return comment_obj
